package com.example.demo.controller;

import com.example.demo.bean.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/updateProduct")
    public String getProduct(@RequestParam("file") MultipartFile file,@RequestParam("name") String name,@RequestParam("price") Integer price){
        try {
            // 调用服务层保存图片
            productService.saveImage(file,name,price);
            // 返回成功信息
            return "文件上传成功: " + file.getOriginalFilename();
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return "文件上传失败: " + e.getMessage();
        }
    }

    @RequestMapping("/products")
    public List<Product> getAllProducts() {
        return productService.getImgAll();
    }

    @RequestMapping("/products/{id}")
    //该注释可以从地址中获取需要的数据
    public Product getProductById(@PathVariable Long id) {
        return productService.getProductById(id);
    }

//修改产品的方法
@PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(
        @PathVariable Long id,
        @RequestBody Product productUpdate) {
    Product updatedProduct = productService.updateProduct(id, productUpdate);
    if (updatedProduct != null) {
        return ResponseEntity.ok(updatedProduct);
    }
    return ResponseEntity.notFound().build();
}
    @DeleteMapping("/products/{id}")  // 使用DELETE方法
    public ResponseEntity<Product> deleteProduct(@PathVariable Long id) {
        Product product = productService.deleteProduct(id);
        if (product != null) {
            return ResponseEntity.ok(product);
        }
        return ResponseEntity.notFound().build();
    }
}

